package com.android.kmlmrg.listener;

import java.util.ArrayList;
import java.util.List;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

import com.android.kmlmrg.adapter.ContactAdapter;
import com.android.kmlmrg.model.User;
import com.android.kmlmrg.views.Search;

public class SearchBarListener implements TextWatcher{
	
	private int textlength=0;
	
	private ArrayList<User> list_sort= new ArrayList<User>();
	/** LOG **/
	private static final String LOG_TAG = SearchBarListener.class.getName();
	
	private Search vContext;
	
	public SearchBarListener(Search search){
		vContext = search;
	}
	public void afterTextChanged(Editable s) {
		
	}
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		
	}
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		Log.i(LOG_TAG, "START - onTextChanged");
		EditText search = vContext.getSearchBar();
		List<User> listUser = vContext.getListUser();
		String sequence = search.getText().toString();
		textlength = search.getText().length();
		list_sort.clear();
		for (int position = 0; position < listUser.size(); position++)
		{
			if ((textlength <= listUser.get(position).getNom().length()) || (textlength <= listUser.get(position).getPrenom().length()))
			{
				if(listUser.get(position).getNom().toUpperCase().contains(sequence.toUpperCase())||
					(listUser.get(position).getPrenom().toUpperCase().contains(sequence.toUpperCase())))
				{
					list_sort.add(listUser.get(position));
	            }
	        }
		}
		vContext.getList().setAdapter(new ContactAdapter(vContext,list_sort));
		Log.i(LOG_TAG, "END - onTextChanged");
	}
}
